﻿using Accord.Video.FFMPEG;
using ImageMagick;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mp4PlayApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnShot_Click(object sender, EventArgs e)
        {

            string inputFilePath = @txtInputFile.Text.Trim();
            TimeSpan timestamp = TimeSpan.FromSeconds(Convert.ToInt32(txtShotTimes.Text.Trim())); // 选择的截图时间点
            string outputFilePath = txtOutputFile.Text.Trim();

            TakeScreenshotAtTime(inputFilePath, timestamp, outputFilePath);
            //CompressPngWithMagickNET(outputFilePath, outputFilePath);
            CompressJpg(outputFilePath, outputFilePath, 80);


        }

        static void TakeScreenshotAtTime(string inputFilePath, TimeSpan timestamp, string outputFilePath)
        {
            // 创建VideoFileReader以读取MP4文件
            using (var reader = new VideoFileReader())
            {
                reader.Open(inputFilePath);

                // 计算目标帧的总时间（基于帧率）
                double framesPerSecond = (double)reader.FrameRate;
                double targetTotalSeconds = timestamp.TotalSeconds;

                // 初始化当前累计时间
                double currentTotalSeconds = 0.0;

                // 逐帧读取，直到到达目标时间点或读取完所有帧
                Bitmap screenshot = null;
                while (true)
                {
                    Bitmap frame = reader.ReadVideoFrame();
                    if (frame == null)
                    {
                        Console.WriteLine("End of video reached before target time.");
                        break;
                    }

                    currentTotalSeconds += 1.0 / framesPerSecond;

                    if (currentTotalSeconds >= targetTotalSeconds)
                    {
                        screenshot = frame;
                        break;
                    }
                }

                if (screenshot == null)
                {
                    Console.WriteLine($"Target time is beyond the length of the video.");
                    return;
                }

                // 保存截图到PNG文件
                screenshot.Save(outputFilePath, ImageFormat.Png);
                Console.WriteLine($"Screenshot taken at {timestamp} saved to {outputFilePath}");
            }
        }

        /// <summary>
        /// 图片压缩
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outputFilePath"></param>
        public static void CompressPngWithMagickNET(string inputFilePath, string outputFilePath)
        {

            // 加载原始PNG图片
            using (var image = new MagickImage(inputFilePath))
            {
                // Magick.NET没有直接的“质量”参数，但可以调整压缩等级
                //image.CompressionMethod = CompressionMethod.Deflate; // 默认就是Deflate，此处仅为演示
                image.SetCompression(CompressionMethod.JPEG); // 默认就是Deflate，此处仅为演示
                //image.CompressionQuality = 100; // 范围为0到100，通常保持100以获得最佳压缩效果
                //image.CompressionQuality = 100; // 范围为0到100，通常保持100以获得最佳压缩效果
                image.Resize(new MagickGeometry(480, 360)); // 调整尺寸
                image.Quantize(new QuantizeSettings { Colors = 256 }); // 量化至256色

                // 保存压缩后的PNG图片
                image.Write(outputFilePath);
            }
        }

        public void CompressJpg(string inputFilePath, string outputFilePath, int qualityPercentage)
        {
            // 加载原始JPEG图片
            using (var image = new MagickImage(inputFilePath))
            {
                // 设置压缩质量（范围通常为0到100，值越低压缩程度越高，文件越小，但图像质量损失也越大）
                image.Quality = qualityPercentage;

                image.Resize(new MagickGeometry(600, 450)); // 调整尺寸

                // 保存压缩后的JPEG图片
                image.Write(outputFilePath);
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "All Files|*.*|MP4 File|*.mp4" };

            
            using (openFileDialog)
            {
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtInputFile.Text = openFileDialog.FileName;
                    FileInfo fileInfo = new FileInfo(txtInputFile.Text);
                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.FullName);
                    txtOutputFile.Text = txtOutputFile.Text + fileNameWithoutExtension + ".jpg";

                }
            }
        }
    }
}
